<template>
	<div class="main">
		<div class="main-header" style="display: flex;justify-content: space-between;">
			<div style="display: flex;flex:1;flex-wrap: wrap;gap: 10px;">
				<el-input v-model="searchParamCp.search" placeholder="请输入老师名称" style="width:120px"></el-input>
				<el-input v-model="searchParamCp.search_family" placeholder="家庭成员名称" style="width:120px"></el-input>
				<teacherSelect v-model="searchParamCp.teacher_id" style="width: 130px;"></teacherSelect>
				<el-select v-model="searchParamCp.family_status" placeholder="请选择状态" style="width:200px;margin-left: 10px;">
					<el-option v-show="item.id!=2" v-for="(item, index) in newTypeList" :key="index" :label="item.title" :value="item.id">
					</el-option>
				</el-select>
				<!-- <el-select v-model="searchParamCp.type" placeholder="请选择用户角色" style="width:200px;margin-left: 10px;">
				    <el-option v-for="(item,index) in typeList" :key="index" :label="item.title" :value="item.id">
				    </el-option>
				</el-select> -->

				<!-- <div style="width:340px; margin-left:10px;"  class="ml-10">
					<el-cascader :options="typelist" v-model="searchParamCp.cate_id" :show-all-levels="false"></el-cascader>
				</div> -->

				<!-- <el-select v-model="searchParamCp.status" placeholder="请选择认证状态" style="width:200px;margin-left: 10px;">
				    <el-option v-for="(item,index) in statusList" :key="index" :label="item" :value="index">
				    </el-option>
				</el-select> -->
				<div style="width:340px;" class="ml-10">
					<el-date-picker clearable v-model="searchParamCp.search_time" value-format="timestamp" type="daterange"
						range-separator="至" start-placeholder="订单日期" end-placeholder="订单日期">
					</el-date-picker>
				</div>
				<div style="width:340px;" class="ml-10">
					<el-date-picker clearable v-model="searchParamCp.reply_refound_time" value-format="timestamp" type="daterange"
						range-separator="至" start-placeholder="退款日期" end-placeholder="退款日期">
					</el-date-picker>
				</div>
			</div>
			<div style="display: flex;gap: 10px;">
				<div class="ml-10" style="white-space: nowrap;">
					<el-button v-if="$auth('changeClass')" @click.stop="changeClassRoom()" :disabled="!selection.length"
						type="warning">转班</el-button>
					<el-button type="primary" @click="searchinfo">搜索</el-button>
					<el-button type="primary" @click="reset">重置</el-button>
				</div>
				<!-- <el-button type="primary" @click="add()">添加</el-button> -->
				<!-- <el-upload-file :showfile="false" v-model="importindex"  @click="importExcel()"
				accept=".xlsx" style="margin: 0 10px;" title="导入"></el-upload-file> -->
				<!-- <eluploadfile v-if="$auth('import')" :auto-upload="false" :upload-clear="true" :show-file-list="false" @change="upload" :limit="1" :multiple="false" accept=".xls,.xlsx" class="ml-10">
				    <el-button type="primary" >导入</el-button>
				</eluploadfile> -->
				<el-button type="primary" @click="exportExcel">导出</el-button>
				<!-- <el-button style="margin-left: 10px;"  type="danger" @click="selectdel"
					:disabled="!selection.length">批量删除</el-button> -->
			</div>
		</div>
		<el-table ref="table" class="main-table" header-align="center" border :data="list" :summary-method="getSummaries"
			show-summary @selection-change="onSelectionChange" height="100%" row-key="id"
			header-cell-class-name="main-table-header" @row-click="onRowClick">
			<el-table-column type="selection" width="50"> </el-table-column>
			<el-table-column label="订单号" prop="order_sn" width="180"></el-table-column>
			<!-- <el-table-column  show-overflow-tooltip label="社区名称" prop="mass_name"></el-table-column> -->
			<el-table-column label="课程轮播图" prop="img" width="100">
				<template slot-scope="{row}">
					<el-image style="width:60px;height:60px" :src="row.img?.split(',')[0] || []"
						:preview-src-list="row.img?.split(',')[0] || []">
					</el-image>
				</template>
			</el-table-column>
			<el-table-column show-overflow-tooltip label="社区名称" prop="community_name" width="140"></el-table-column>
			<el-table-column show-overflow-tooltip label="用户名称" prop="name" width="100"></el-table-column>
			<el-table-column show-overflow-tooltip label="家庭成员" prop="family_name" width="100"></el-table-column>
			<el-table-column show-overflow-tooltip label="家庭成员号码" prop="family_mobile" width="100"></el-table-column>
			<el-table-column show-overflow-tooltip label="课程名称" prop="course_name" width="100"></el-table-column>
			<el-table-column show-overflow-tooltip label="老师名称" prop="teacher_name" width="100"></el-table-column>
			<el-table-column show-overflow-tooltip label="实付价格" prop="total_price" width="100"></el-table-column>
			<!-- <el-table-column show-overflow-tooltip label="总价格" prop="total_price"></el-table-column> -->
			<el-table-column show-overflow-tooltip label="积分抵扣价" prop="total_score_price"
				width="100"></el-table-column></el-table-column>
			<el-table-column show-overflow-tooltip label="课时" prop="class_hour" width="80"></el-table-column>
			<el-table-column show-overflow-tooltip label="联系电话" prop="phoneNumber" width="100"></el-table-column>
			<el-table-column label="是否转班" prop="is_zb" width="100">
				<template slot-scope="{row}">
					<!-- is_zb 0未转班1已转班 -->
					<el-tag :type="row.is_zb == 1 ? 'danger' : ''">
						{{ row.is_zb == 1 ? '已转班' : '未转班' }}
					</el-tag>
				</template>
			</el-table-column>
			<el-table-column label="报名状态" width="100">
				<!--0未支付1已支付/待核销3已核销/待评价4已评价/已完成5已退款6已取消  -->
				<template slot-scope="{row}">
					<el-tag :type="newTypeList[row.family_status].type">{{ newTypeList[row.family_status].title }}</el-tag>
				</template>
			</el-table-column>
			<el-table-column label="创建时间" prop="create_time" width='160'>
				<template slot-scope="{row}">
					{{ row.create_time | formatDate }}
				</template>
			</el-table-column>
			<el-table-column label="退款时间" prop="create_time" width='160'>
				<template slot-scope="{row}">
					<span v-if="row.reply_refound_time">{{ row.reply_refound_time | formatDate }}</span>
				</template>
			</el-table-column>
			<el-table-column label="操作" fixed="right" width="200">
				<template slot-scope="{row}">
					<el-button type="primary" @click.stop="openHx(row)">明细</el-button>
					<el-button type="warning" v-if="row.family_status == 6 && $auth('refund')"
						@click.stop="examineRefund(row)">退款审核</el-button>
					<!-- <el-button type="warning" @click.stop="add(row)">详情</el-button> -->
				</template>
			</el-table-column>
		</el-table>
		<el-pagination class="main-pagination" :current-page.sync="searchParam.page" :page-size="searchParam.limit"
			:total="searchParam.total" @current-change="onCurrentChange" layout="total,jumper,prev,pager,next">
		</el-pagination>
		<el-dialog :title="title" :key="formDataStatus" :visible.sync="centerDialogVisible" @close="onDialogClose"
			width="70%">
			<add @close="close" :formData="userinfo" @search="addcommunity"></add>
		</el-dialog>

		<hxList :list="hxList" ref="hxList"></hxList>
		<!-- 转班 -->
		<changeClass ref="changeClass" @confirm="getList"></changeClass>
	</div>
</template>
<script>
// import companyCate from '@/components/company-cate.vue'
// import supervisorSelect from '@/components/supervisor-select.vue'auth
import add from './components/add.vue'
import teacherSelect from '@/components/teacher-select.vue'
import { imghttp, get, post, del } from '@/assets/js/http'
import hxList from './components/hxList.vue'
import changeClass from './components/changeClass.vue'
// import eluploadfile from '../../components/el-upload-file.vue'
export default {
	components: { add, teacherSelect, hxList, changeClass },
	data() {
		return {
			list: [],
			selection: [],
			addShow: false, //添加显示
			centerDialogVisible: false, //详情弹窗
			title: '', //弹窗标题
			userinfo: {}, //用户信息
			newTypeList: {
				0:{ id: 0, title: '未支付', type: '' },
				1:{ id: 1, title: '已支付', type: 'success' },
				2:{ id: 2, title: '已核销', type: 'success' },
				3:{ id: 3, title: '已退款', type: 'danger' },
				4:{ id: 4, title: '已取消', type: 'info' },
				5:{ id: 5, title: '已评价/已完成', type: 'success' },
				6:{ id: 6, title: '退款中', type: 'warning' }
			},//0待支付1已支付2已核销3已退款4已取消5已评价/已完成
			typeList: [
				{ id: 0, title: '未支付' },
				{ id: 1, title: '待核销' },
				{ id: 3, title: '已核销' },
				{ id: 4, title: '已评价' },
				{ id: 5, title: '已退款' },
				{ id: 6, title: '已取消' }
			],
			//0未支付1已支付/待核销3已核销/待评价4已评价/已完成5已退款6已取消 
			statusList: ['未认证', '认证待审核', '认证通过', '认证驳回'], //认证状态 0未认证 1认证待审核 2认证通过 3认证驳回
			searchParam: {
				page: 1,
				limit: 20,
				total: 0,
				cadre_id: '',
				search_time: [],
				cate_id: [],
				status: '',
				family_status: '',
				type: '',
				search: '',
				reply_refound_time:[]
			},
			searchParamCp: {
				status: '',
				page: 1,
				limit: 20,
				total: 0,
				cadre_id: '',
				reply_refound_time:[],
				search_time: [],
				cate_id: [],
				status: '',
				family_status: '',
				type: '',
				search: '',
			},
			formDataStatus: false,
			imgs: [],
			typelist: [],//分类列表
			props: {
				label: "name",
				value: "id",
				children: "child",
				checkStrictly: true
			},
			sign_total_hour: '',
			sign_total_price: '',
			sign_total_score: '',
			total_count: '',
			hxList: [],
		}
	},

	updated() {
		this.$nextTick(() => {
			this.$refs.table.doLayout();
		});
	},
	created() {
		Object.assign(this.searchParam, this.$route.query ? this.$route.query : {})
		Object.assign(this.searchParamCp, this.$route.query ? this.$route.query : {})

		if(this.$route.query.family_status=='1,2,5'){this.searchParam.family_status = this.$route.query.family_status;this.searchParamCp.family_status = ''}

		this.getList()
		this.getcateList()
	},
	watch: {
		'$route': {
			deep: true,
			handler() {
				this.reset()
			}
		},
	},
	methods: {
		// 退款审核
		examineRefund(row) {
			this.$confirm('确定要退款审核吗?', '提示', {
				confirmButtonText: '同意退款',
				cancelButtonText: '拒绝退款',
				cancelButtonClass: 'el-button el-button--warning',
				confirmButtonClass: 'el-button el-button--danger',
				type: 'warning',
				distinguishCancelAndClose: true,
				center: true
			}).then(() => {
				this.requestRefund(row.order_id, row.family_id, 1)
			}).catch((action) => {
				// 拒绝退款
				if (action == 'cancel') {
					this.requestRefund(row.order_id, row.family_id, 2)
				} else {
				}
			})
		},
		requestRefund(id, fid, type) {
			this.$confirm(`确定要${type == 1 ? '同意' : '拒绝'}该退款吗?操作后不可更改`, '提示', {

			}).then(async () => {
				try {
					await post({
						url: '/admin/project.Course/admin_refund',
						loading: true,
						data: {
							status: type,
							orderid: id,
							family_id: fid
						}
					})
					this.$message({
						type: 'success',
						message: '操作成功'
					})
					this.getList()
				} catch (err) {

				}
			})
		},
		changeClassRoom() {
			if (!this.selection.length) {
				return
			}
			let map = new Map()
			this.selection.forEach((item) => {
				map.set(item.order_sn)
			})
			if ([...map.keys()].length > 1) {
				this.$message({
					type: 'warning',
					message: '只能选择相同订单号的课程',
				})
				return
			}

			this.$refs.changeClass.open(this.selection.map(item => item.id), this.selection[0].order_id)
		},
		openHx(row) {
			this.hxList = row.family
			this.$refs.hxList.open()
		},
		//获取社区列表
		async getList() {
			this.$loading()
			// let { list,total } = 
			await get({
				url: '/admin/project.Course/buy_order',
				params: {
					...this.searchParam,
					...{
						server_type: this.$route.query.type ? 2 : 1,
						search_time:  this.searchParam.search_time && this.searchParam.search_time.length ? this.searchParam.search_time.map(item => item / 1000) : '',
						reply_refound_time: this.searchParam.reply_refound_time && this.searchParam.reply_refound_time.length ? this.searchParam.reply_refound_time.map(item => item / 1000) : '',
					}
				}
			}).then(res => {
				this.list = res.list.list
				this.searchParam.total = res.total
				this.sign_total_hour = res.list.sign_total_hour
				this.sign_total_price = res.list.sign_total_price
				this.sign_total_score = res.list.sign_total_score
				this.total_count = res.list.total_count
				this.importindex = []
				this.$loading().close()
			})
		},
		//添加/编辑弹窗
		add(row) {
			if (row) { //编辑
				this.centerDialogVisible = true
				this.title = "课程明细"
				// this.userinfo = res.row
				this.userinfo = JSON.parse(JSON.stringify(row.family))
				// get({
				// 	url: '/admin/project.Course/edit',
				// 	params: {
				// 		id: row.id
				// 	}
				// }).then(res => {
				// 	this.userinfo = res.row
				// 	this.userinfo.img = [{
				// 		name: res.row.img,
				// 		url: res.row.img,
				// 	}]
				// 	console.log(this.userinfo.img,'this.userinfo.img')
				// })

			} else { //添加
				this.userinfo = {}
				this.centerDialogVisible = true
				this.title = "添加课程"
			}
			this.formDataStatus = true;
		},
		//添加课程
		addcommunity(result) {
			const info = JSON.parse(JSON.stringify(result))
			console.log
			info.img.forEach(item => {
				this.imgs.push(item.url)
			})
			info.img = this.imgs.join(',')
			info.desc = ''
			console.log(info, info.img, this.imgs)
			// return
			if (info.id) {
				post({
					url: '/admin/project.Course/edit',
					data: info
				}).then(res => {
					this.close()
					this.getList()
				})
			} else {
				post({
					url: '/admin/project.Course/add',
					data: info
				}).then(res => {
					this.close()
					this.getList()
				})
			}
		},
		async getcateList() {
			// this.$loading()
			// let { list,total } = 
			await get({
				url: '/admin/project.CourseCategory/cate_list',
				params: {
					limit: 999
					// ...this.searchParam,
					// ...{
					// 	server_type: this.$route.query.type ? 2 : 1,
					// 	// type:2,//1专业2标签
					// 	// search_time:this.searchParam.search_time.length?this.searchParam.search_time.join(' - '):''
					// }
				}
			}).then(res => {
				this.typelist = res
				// this.searchParam.total = res.total
				// this.importindex = []
				// this.$loading().close()
			})
		},
		//关闭弹窗
		close() {
			this.centerDialogVisible = false
		},
		reset() {
			this.searchParamCp = this.$options.data().searchParam
			this.searchParam = this.$options.data().searchParam
			this.getList()
		},
		searchinfo() {
			this.searchParam.page = 1
			this.searchParam = {
				...this.searchParam,
				...this.searchParamCp
			}
			this.getList()
		},
		onCurrentChange() {
			this.getList()
		},
		onRowClick(row) {
			this.$refs.table.toggleRowSelection(row);
		},
		onSelectionChange(selection) {
			this.selection = selection;
		},
		selectdel() {
			this.$confirm(
				`此操作将永久删除该${this.selection.length}个课程, 是否继续?`,
				"提示", {
				confirmButtonText: "确定",
				cancelButtonText: "取消",
				type: "warning"
			}
			)
				.then(async () => {
					let query = "?";
					for (let i = 0; i < this.selection.length; i++) {
						const item = this.selection[i];
						if (i > 0) {
							query += "&ids[]=" + item.id;
						} else {
							query += "ids[]=" + item.id;
						}
					}
					await del({
						url: "/admin/project.Course/del" + query,
						successTip: true,
						loading: true
					});
					this.getList()
				})
				.catch(() => {
					this.$refs.table.clearSelection();
				});
		},
		//导出
		async exportExcel() {
			this.$loading()
			let res = await get({
				export: true,
				url: '/api/Realmerit/course_export',
				params: {
					...this.searchParam,
					...{
						server_type: this.$route.query.type ? 2 : 1,
						search_time:  this.searchParam.search_time && this.searchParam.search_time.length ? this.searchParam.search_time.map(item => item / 1000) : '',
						reply_refound_time: this.searchParam.reply_refound_time && this.searchParam.reply_refound_time.length ? this.searchParam.reply_refound_time.map(item => item / 1000) : '',
					}
				}
			})
			let a = document.createElement('a');
			var url = URL.createObjectURL(res);
			a.href = url;
			a.click();
			this.$loading().close()
		},
		//导入
		async upload({
			raw
		}) {
			this.$loading({
				text: '导入中 请等待...'
			})
			await imghttp({
				url: '/admin/basic.Masses/import',
				data: {
					file: raw
				},
				successTip: true
			})
			this.getList()
			this.$loading().close()
		},
		onDialogClose() {

		},
		getSummaries(param) {
			const { columns, data } = param;
			const sums = [];
			columns.forEach((column, index) => {
				if (index === 0) {
					sums[index] = '总计';
					return;
				}
				if (index === 9) {
					sums[index] = '总课时：' + this.sign_total_hour + '';
					return;
				}
				if (index === 6) {
					sums[index] = '支付总价格：' + this.sign_total_price + '元';
					return;
				}
				if (index === 8) {
					sums[index] = '积分总抵扣：' + this.sign_total_score;
					return;
				}
				if (index === 1) {
					sums[index] = '购买数量：' + this.total_count;
					return;
				}

			});
			console.log(sums)
			return sums;
		}

	}
}
</script>

<style>
.el-date-editor .el-range-separator {
	padding: 0;
}
</style>
